package com.kui.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kui.entity.Wenxian;
import com.kui.service.WenxianService;

public class DownServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String dname = request.getParameter("dname");
		if(dname == null || "".equals(dname)){
			response.sendRedirect("wenxian.jspx");
		}else{
			final String PATH = getServletContext().getRealPath("/");
			File file = new File(PATH +  "/upload/" +dname);
			
			if(!file.exists()){
				response.sendError(404,"文件不可用或已删除");
			}else {
				WenxianService ws = new WenxianService();
				Wenxian w = ws.findWenxianByDname(dname);
				if(w == null){
					response.sendError(404);
					return;
				}
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
				
				byte[] buffer = new byte[4096];
				
				response.setContentType("application/octet-stream");
				response.setContentLength((int)w.getSize());
				String encodedfileName = new String((w.getName()+"."+w.getType()).getBytes("gbk"), "ISO8859-1");
				//String encodedfileName = w.getName()+"."+w.getType();
				
				response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
				
				OutputStream os = response.getOutputStream(); //获取响应输出流
				
				int len = -1;
				while((len = bis.read(buffer)) != -1) {
					os.write(buffer, 0, len);
				}
				
				os.flush();
				os.close();
				bis.close();
				
			}
		}

	}

	
}
